using DocumentManager.Models;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace DocumentManager;

/// <summary>
/// 样式设置窗口
/// </summary>
public partial class StyleSettingsWindow : Window
{
    private ExportStyle _currentStyle;
    private ExportStyle[] _presetStyles;
    private bool _isInitializing = true;

    public ExportStyle SelectedStyle => _currentStyle;
    
    public StyleSettingsWindow(ExportStyle? initialStyle = null)
    {
        InitializeComponent();
        
        _currentStyle = initialStyle?.DeepClone() ?? ExportStyle.CreateDefault();
        _presetStyles = ExportStyle.GetAllPresets();
        
        InitializeControls();
        LoadCurrentStyle();
        
        _isInitializing = false;
        
        // 更新删除按钮状态
        UpdateDeleteButtonState();
    }

    private void InitializeControls()
    {
        // 初始化字体列表
        var fonts = new[] { "微软雅黑", "宋体", "黑体", "楷体", "Arial", "Times New Roman", "Calibri", "Georgia" };
        
        DocTitleFontComboBox.ItemsSource = fonts;
        BodyFontComboBox.ItemsSource = fonts;
        CaptionFontComboBox.ItemsSource = fonts;
        
        // 初始化对齐方式
        var alignments = Enum.GetNames(typeof(Models.TextAlignment));
        DocTitleAlignComboBox.ItemsSource = alignments;
        BodyAlignComboBox.ItemsSource = alignments;
        
        var imageAlignments = Enum.GetNames(typeof(ImageAlignment));
        ImageAlignComboBox.ItemsSource = imageAlignments;
        CaptionAlignComboBox.ItemsSource = imageAlignments;
        
        // 初始化页面设置
        PageSizeComboBox.ItemsSource = Enum.GetNames(typeof(PageSize));
        OrientationComboBox.ItemsSource = Enum.GetNames(typeof(PageOrientation));
        
        // 初始化预设样式
        PresetComboBox.ItemsSource = _presetStyles;
        PresetComboBox.DisplayMemberPath = "Name";
        PresetComboBox.SelectedIndex = 0;
        
        // 创建标题样式控件
        CreateHeadingStyleControls();
    }

    private void CreateHeadingStyleControls()
    {
        HeadingStylesPanel.Children.Clear();
        
        for (int i = 0; i < 6; i++)
        {
            var level = i + 1;
            var border = new Border
            {
                BorderBrush = new SolidColorBrush(Colors.LightGray),
                BorderThickness = new Thickness(1),
                Margin = new Thickness(5),
                Padding = new Thickness(10)
            };
            
            var grid = new Grid();
            grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Auto) });
            grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
            grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Auto) });
            grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
            grid.RowDefinitions.Add(new RowDefinition());
            grid.RowDefinitions.Add(new RowDefinition());
            grid.RowDefinitions.Add(new RowDefinition());
            
            // 标题标签
            var titleLabel = new Label { Content = $"标题 {level}:", FontWeight = FontWeights.Bold };
            Grid.SetRow(titleLabel, 0);
            Grid.SetColumn(titleLabel, 0);
            Grid.SetColumnSpan(titleLabel, 4);
            grid.Children.Add(titleLabel);
            
            // 字体
            var fontLabel = new Label { Content = "字体:" };
            Grid.SetRow(fontLabel, 1);
            Grid.SetColumn(fontLabel, 0);
            grid.Children.Add(fontLabel);
            
            var fontCombo = new ComboBox 
            { 
                Name = $"Heading{level}FontComboBox", 
                Width = 120,
                ItemsSource = DocTitleFontComboBox.ItemsSource
            };
            Grid.SetRow(fontCombo, 1);
            Grid.SetColumn(fontCombo, 1);
            grid.Children.Add(fontCombo);
            
            // 字号
            var sizeLabel = new Label { Content = "字号:" };
            Grid.SetRow(sizeLabel, 1);
            Grid.SetColumn(sizeLabel, 2);
            grid.Children.Add(sizeLabel);
            
            var sizeTextBox = new TextBox 
            { 
                Name = $"Heading{level}SizeTextBox", 
                Width = 60 
            };
            Grid.SetRow(sizeTextBox, 1);
            Grid.SetColumn(sizeTextBox, 3);
            grid.Children.Add(sizeTextBox);
            
            // 颜色
            var colorLabel = new Label { Content = "颜色:" };
            Grid.SetRow(colorLabel, 2);
            Grid.SetColumn(colorLabel, 0);
            grid.Children.Add(colorLabel);
            
            var colorPanel = new StackPanel { Orientation = Orientation.Horizontal };
            var colorTextBox = new TextBox 
            { 
                Name = $"Heading{level}ColorTextBox", 
                Width = 80 
            };
            var colorButton = new System.Windows.Controls.Button 
            { 
                Name = $"Heading{level}ColorButton", 
                Width = 30, 
                Height = 25, 
                Margin = new Thickness(5, 0, 0, 0),
                Tag = level
            };
            colorButton.Click += ColorButton_Click;
            
            colorPanel.Children.Add(colorTextBox);
            colorPanel.Children.Add(colorButton);
            Grid.SetRow(colorPanel, 2);
            Grid.SetColumn(colorPanel, 1);
            grid.Children.Add(colorPanel);
            
            // 复选框
            var boldCheckBox = new CheckBox 
            { 
                Name = $"Heading{level}BoldCheckBox", 
                Content = "粗体", 
                Margin = new Thickness(0, 5, 10, 5) 
            };
            var italicCheckBox = new CheckBox 
            { 
                Name = $"Heading{level}ItalicCheckBox", 
                Content = "斜体", 
                Margin = new Thickness(0, 5, 0, 5) 
            };
            
            var checkPanel = new StackPanel { Orientation = Orientation.Horizontal };
            checkPanel.Children.Add(boldCheckBox);
            checkPanel.Children.Add(italicCheckBox);
            Grid.SetRow(checkPanel, 2);
            Grid.SetColumn(checkPanel, 2);
            Grid.SetColumnSpan(checkPanel, 2);
            grid.Children.Add(checkPanel);
            
            border.Child = grid;
            HeadingStylesPanel.Children.Add(border);
            
            // 注册控件名称
            RegisterName(fontCombo.Name, fontCombo);
            RegisterName(sizeTextBox.Name, sizeTextBox);
            RegisterName(colorTextBox.Name, colorTextBox);
            RegisterName(colorButton.Name, colorButton);
            RegisterName(boldCheckBox.Name, boldCheckBox);
            RegisterName(italicCheckBox.Name, italicCheckBox);
        }
    }

    private void LoadCurrentStyle()
    {
        _isInitializing = true;
        
        // 文档标题
        DocTitleFontComboBox.SelectedItem = _currentStyle.DocumentTitle.FontName;
        DocTitleSizeTextBox.Text = _currentStyle.DocumentTitle.FontSize.ToString();
        DocTitleColorTextBox.Text = _currentStyle.DocumentTitle.Color;
        DocTitleAlignComboBox.SelectedItem = _currentStyle.DocumentTitle.Alignment.ToString();
        DocTitleBoldCheckBox.IsChecked = _currentStyle.DocumentTitle.IsBold;
        DocTitleItalicCheckBox.IsChecked = _currentStyle.DocumentTitle.IsItalic;
        UpdateColorButton(DocTitleColorButton, _currentStyle.DocumentTitle.Color);
        
        // 各级标题
        for (int i = 0; i < 6; i++)
        {
            var level = i + 1;
            var heading = _currentStyle.HeadingStyles[i];
            
            var fontCombo = FindName($"Heading{level}FontComboBox") as ComboBox;
            var sizeTextBox = FindName($"Heading{level}SizeTextBox") as TextBox;
            var colorTextBox = FindName($"Heading{level}ColorTextBox") as TextBox;
            var colorButton = FindName($"Heading{level}ColorButton") as Button;
            var boldCheckBox = FindName($"Heading{level}BoldCheckBox") as CheckBox;
            var italicCheckBox = FindName($"Heading{level}ItalicCheckBox") as CheckBox;
            
            if (fontCombo != null) fontCombo.SelectedItem = heading.FontName;
            if (sizeTextBox != null) sizeTextBox.Text = heading.FontSize.ToString();
            if (colorTextBox != null) colorTextBox.Text = heading.Color;
            if (colorButton != null) UpdateColorButton(colorButton, heading.Color);
            if (boldCheckBox != null) boldCheckBox.IsChecked = heading.IsBold;
            if (italicCheckBox != null) italicCheckBox.IsChecked = heading.IsItalic;
        }
        
        // 正文样式
        BodyFontComboBox.SelectedItem = _currentStyle.BodyText.FontName;
        BodySizeTextBox.Text = _currentStyle.BodyText.FontSize.ToString();
        BodyColorTextBox.Text = _currentStyle.BodyText.Color;
        BodyAlignComboBox.SelectedItem = _currentStyle.BodyText.Alignment.ToString();
        BodyBoldCheckBox.IsChecked = _currentStyle.BodyText.IsBold;
        BodyItalicCheckBox.IsChecked = _currentStyle.BodyText.IsItalic;
        LineSpacingTextBox.Text = _currentStyle.BodyText.LineSpacing.ToString();
        ParagraphSpacingTextBox.Text = _currentStyle.BodyText.ParagraphSpacing.ToString();
        UpdateColorButton(BodyColorButton, _currentStyle.BodyText.Color);
        
        // 页面设置
        PageSizeComboBox.SelectedItem = _currentStyle.PageSettings.PageSize.ToString();
        OrientationComboBox.SelectedItem = _currentStyle.PageSettings.Orientation.ToString();
        TopMarginTextBox.Text = _currentStyle.PageSettings.Margins.Top.ToString();
        BottomMarginTextBox.Text = _currentStyle.PageSettings.Margins.Bottom.ToString();
        LeftMarginTextBox.Text = _currentStyle.PageSettings.Margins.Left.ToString();
        RightMarginTextBox.Text = _currentStyle.PageSettings.Margins.Right.ToString();
        
        // 图片设置
        ImageAlignComboBox.SelectedItem = _currentStyle.ImageStyle.Alignment.ToString();
        ShowCaptionCheckBox.IsChecked = _currentStyle.ImageStyle.ShowCaption;
        MaxWidthTextBox.Text = _currentStyle.ImageStyle.MaxWidth.ToString();
        MaxHeightTextBox.Text = _currentStyle.ImageStyle.MaxHeight.ToString();
        CaptionFontComboBox.SelectedItem = _currentStyle.ImageStyle.CaptionFontName;
        CaptionSizeTextBox.Text = _currentStyle.ImageStyle.CaptionFontSize.ToString();
        CaptionColorTextBox.Text = _currentStyle.ImageStyle.CaptionColor;
        CaptionAlignComboBox.SelectedItem = _currentStyle.ImageStyle.CaptionAlignment.ToString();
        UpdateColorButton(CaptionColorButton, _currentStyle.ImageStyle.CaptionColor);
        
        _isInitializing = false;
        
        // 初始化预览
        RefreshPreview();
    }

    private void UpdateColorButton(System.Windows.Controls.Button button, string colorHex)
    {
        try
        {
            var color = (System.Windows.Media.Color)ColorConverter.ConvertFromString(colorHex);
            button.Background = new SolidColorBrush(color);
        }
        catch
        {
            button.Background = new SolidColorBrush(Colors.White);
        }
    }

    private void ColorButton_Click(object sender, RoutedEventArgs e)
    {
        if (sender is System.Windows.Controls.Button button)
        {
            // 简化的颜色选择 - 弹出输入框让用户输入颜色值
            TextBox? colorTextBox = null;
            if (button.Name.Contains("DocTitle"))
                colorTextBox = DocTitleColorTextBox;
            else if (button.Name.Contains("Body"))
                colorTextBox = BodyColorTextBox;
            else if (button.Name.Contains("Caption"))
                colorTextBox = CaptionColorTextBox;
            else if (button.Name.Contains("Heading"))
            {
                var level = button.Tag?.ToString();
                colorTextBox = FindName($"Heading{level}ColorTextBox") as TextBox;
            }
            
            if (colorTextBox != null)
            {
                var inputDialog = new InputDialog("请输入颜色值 (如: #FF0000 或 Red):", "选择颜色", colorTextBox.Text);
                if (inputDialog.ShowDialog() == true && !string.IsNullOrWhiteSpace(inputDialog.Result))
                {
                    colorTextBox.Text = inputDialog.Result;
                    UpdateColorButton(button, inputDialog.Result);
                }
            }
        }
    }

    private void PresetComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (_isInitializing)
            return;
            
        // 更新删除按钮的状态
        UpdateDeleteButtonState();
        
        if (PresetComboBox.SelectedItem is not ExportStyle selectedPreset)
            return;
        
        // 询问是否应用预设
        var result = MessageBox.Show("是否应用选中的预设样式？这将覆盖当前的设置。", 
            "应用预设", MessageBoxButton.YesNo, MessageBoxImage.Question);
        
        if (result == MessageBoxResult.Yes)
        {
            _currentStyle = selectedPreset.DeepClone();
            LoadCurrentStyle();
        }
    }
    
    private void UpdateDeleteButtonState()
    {
        if (DeletePresetButton == null || PresetComboBox.SelectedItem == null)
            return;
            
        var selectedPreset = PresetComboBox.SelectedItem as ExportStyle;
        if (selectedPreset == null)
        {
            DeletePresetButton.IsEnabled = false;
            return;
        }
        
        // 系统预设不能删除
        var systemPresets = ExportStyle.CreatePresetStyles();
        var isSystemPreset = systemPresets.Any(p => p.Name == selectedPreset.Name);
        DeletePresetButton.IsEnabled = !isSystemPreset;
    }
    
    private void DeletePreset_Click(object sender, RoutedEventArgs e)
    {
        if (PresetComboBox.SelectedItem is not ExportStyle selectedPreset)
            return;
            
        // 检查是否为系统预设
        var systemPresets = ExportStyle.CreatePresetStyles();
        var isSystemPreset = systemPresets.Any(p => p.Name == selectedPreset.Name);
        
        if (isSystemPreset)
        {
            MessageBox.Show("系统预设不能删除", "删除失败", 
                MessageBoxButton.OK, MessageBoxImage.Warning);
            return;
        }
        
        // 确认删除
        var result = MessageBox.Show($"确定要删除预设 '{selectedPreset.Name}' 吗？\n此操作无法撤销。", 
            "确认删除", MessageBoxButton.YesNo, MessageBoxImage.Question);
            
        if (result == MessageBoxResult.Yes)
        {
            try
            {
                if (ExportStyle.DeleteUserPreset(selectedPreset.Name))
                {
                    // 刷新预设列表
                    RefreshPresetsList();
                    
                    MessageBox.Show($"预设 '{selectedPreset.Name}' 已删除", "删除成功", 
                        MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                {
                    MessageBox.Show("删除预设失败", "删除失败", 
                        MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除预设失败: {ex.Message}", "删除失败", 
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }

    private void ApplyPreset_Click(object sender, RoutedEventArgs e)
    {
        if (PresetComboBox.SelectedItem is ExportStyle selectedPreset)
        {
            _currentStyle = selectedPreset.DeepClone();
            LoadCurrentStyle();
        }
    }

    private void SaveAsPreset_Click(object sender, RoutedEventArgs e)
    {
        var inputWindow = new InputDialog("请输入预设名称:", "保存预设", "自定义样式");
        if (inputWindow.ShowDialog() == true && !string.IsNullOrWhiteSpace(inputWindow.Result))
        {
            var presetName = inputWindow.Result.Trim();
            
            // 检查名称是否已存在
            if (ExportStyle.PresetNameExists(presetName))
            {
                var result = MessageBox.Show($"预设名称 '{presetName}' 已存在，是否覆盖？", 
                    "确认覆盖", MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (result != MessageBoxResult.Yes)
                    return;
            }
            
            try
            {
                SaveCurrentSettings();
                _currentStyle.Name = presetName;
                _currentStyle.SaveAsUserPreset();
                
                // 刷新预设列表
                RefreshPresetsList();
                
                // 选中新保存的预设
                var newPresetIndex = Array.FindIndex(_presetStyles, p => p.Name == presetName);
                if (newPresetIndex >= 0)
                {
                    PresetComboBox.SelectedIndex = newPresetIndex;
                }
                
                MessageBox.Show($"预设 '{presetName}' 已保存", "保存成功", 
                    MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存预设失败: {ex.Message}", "保存失败", 
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }

    private void Preview_Click(object sender, RoutedEventArgs e)
    {
        SaveCurrentSettings();
        
        // 切换到预览标签页
        MainTabControl.SelectedIndex = 4; // 预览标签页是第5个标签页（0-基础索引）
        
        RefreshPreview();
    }

    private void RefreshPreview_Click(object sender, RoutedEventArgs e)
    {
        SaveCurrentSettings();
        RefreshPreview();
    }

    private void PreviewType_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (!_isInitializing)
        {
            RefreshPreview();
        }
    }

    private void RefreshPreview()
    {
        if (PreviewPanel == null || PreviewTypeComboBox == null)
            return;

        PreviewPanel.Children.Clear();
        
        var selectedType = (PreviewTypeComboBox.SelectedItem as ComboBoxItem)?.Content?.ToString();
        
        switch (selectedType)
        {
            case "全部样式":
                CreateFullPreview();
                break;
            case "标题样式":
                CreateHeadingPreview();
                break;
            case "正文样式":
                CreateBodyPreview();
                break;
            case "图片样式":
                CreateImagePreview();
                break;
            default:
                CreateFullPreview();
                break;
        }
    }

    private void CreateFullPreview()
    {
        // 文档标题预览
        var docTitleBlock = CreateStyledTextBlock("样式预览文档", _currentStyle.DocumentTitle);
        docTitleBlock.Margin = new Thickness(0, 0, 0, 20);
        PreviewPanel.Children.Add(docTitleBlock);

        // 各级标题预览
        for (int i = 0; i < 6; i++)
        {
            var level = i + 1;
            var headingBlock = CreateStyledTextBlock($"{level}级标题样式预览", _currentStyle.HeadingStyles[i]);
            headingBlock.Margin = new Thickness(0, 10, 0, 5);
            PreviewPanel.Children.Add(headingBlock);
        }

        // 正文预览
        var bodyText = "这是正文样式的预览。正文样式用于文档的主要内容显示，包括字体、字号、颜色、对齐方式等设置。您可以通过调整这些参数来获得理想的文档显示效果。";
        var bodyBlock = CreateStyledTextBlock(bodyText, _currentStyle.BodyText);
        bodyBlock.Margin = new Thickness(0, 10, 0, 5);
        bodyBlock.TextWrapping = TextWrapping.Wrap;
        PreviewPanel.Children.Add(bodyBlock);

        // 图片说明预览
        if (_currentStyle.ImageStyle.ShowCaption)
        {
            var captionBlock = CreateImageCaptionBlock("图片说明: 这是图片说明文字的样式预览");
            captionBlock.Margin = new Thickness(0, 10, 0, 5);
            PreviewPanel.Children.Add(captionBlock);
        }
    }

    private void CreateHeadingPreview()
    {
        // 文档标题
        var docTitleBlock = CreateStyledTextBlock("文档标题样式", _currentStyle.DocumentTitle);
        docTitleBlock.Margin = new Thickness(0, 0, 0, 20);
        PreviewPanel.Children.Add(docTitleBlock);

        // 各级标题
        for (int i = 0; i < 6; i++)
        {
            var level = i + 1;
            var headingBlock = CreateStyledTextBlock($"标题{level}: 这是{level}级标题的样式预览", _currentStyle.HeadingStyles[i]);
            headingBlock.Margin = new Thickness(0, 15, 0, 8);
            PreviewPanel.Children.Add(headingBlock);
            
            // 添加标题级别说明
            var infoBlock = new TextBlock
            {
                Text = $"字体: {_currentStyle.HeadingStyles[i].FontName}, 字号: {_currentStyle.HeadingStyles[i].FontSize}, 颜色: {_currentStyle.HeadingStyles[i].Color}",
                FontSize = 10,
                Foreground = new SolidColorBrush(Colors.Gray),
                Margin = new Thickness(0, 0, 0, 10)
            };
            PreviewPanel.Children.Add(infoBlock);
        }
    }

    private void CreateBodyPreview()
    {
        var bodyTitle = CreateStyledTextBlock("正文样式预览", _currentStyle.DocumentTitle);
        bodyTitle.Margin = new Thickness(0, 0, 0, 20);
        PreviewPanel.Children.Add(bodyTitle);

        // 多段正文示例
        var paragraphs = new[]
        {
            "这是第一段正文内容。通过调整正文样式，您可以控制文档主要内容的显示效果，包括字体系列、字号大小、文字颜色、段落对齐方式等重要属性。",
            "这是第二段正文内容，用于展示段落间距和行距的效果。适当的间距设置可以让文档更加美观易读，提升整体的视觉体验。",
            "第三段内容展示了当前样式设置下的文本渲染效果。您可以实时调整设置并观察预览变化，以便找到最适合的样式配置。"
        };

        foreach (var text in paragraphs)
        {
            var block = CreateStyledTextBlock(text, _currentStyle.BodyText);
            block.TextWrapping = TextWrapping.Wrap;
            block.Margin = new Thickness(0, 0, 0, _currentStyle.BodyText.ParagraphSpacing);
            block.LineHeight = _currentStyle.BodyText.FontSize * _currentStyle.BodyText.LineSpacing;
            PreviewPanel.Children.Add(block);
        }

        // 样式信息
        var infoText = $"字体: {_currentStyle.BodyText.FontName} | 字号: {_currentStyle.BodyText.FontSize} | " +
                      $"颜色: {_currentStyle.BodyText.Color} | 对齐: {_currentStyle.BodyText.Alignment} | " +
                      $"行距: {_currentStyle.BodyText.LineSpacing} | 段距: {_currentStyle.BodyText.ParagraphSpacing}";
        
        var infoBlock = new TextBlock
        {
            Text = infoText,
            FontSize = 10,
            Foreground = new SolidColorBrush(Colors.Gray),
            Margin = new Thickness(0, 20, 0, 0),
            TextWrapping = TextWrapping.Wrap
        };
        PreviewPanel.Children.Add(infoBlock);
    }

    private void CreateImagePreview()
    {
        var title = CreateStyledTextBlock("图片样式预览", _currentStyle.DocumentTitle);
        title.Margin = new Thickness(0, 0, 0, 20);
        PreviewPanel.Children.Add(title);

        // 模拟图片框
        var imageBorder = new Border
        {
            Width = Math.Min(_currentStyle.ImageStyle.MaxWidth, 200),
            Height = Math.Min(_currentStyle.ImageStyle.MaxHeight, 150),
            BorderBrush = new SolidColorBrush(Colors.LightGray),
            BorderThickness = new Thickness(2),
            Background = new SolidColorBrush(Colors.LightBlue),
            Margin = new Thickness(0, 10, 0, 10)
        };

        var imageText = new TextBlock
        {
            Text = "图片预览区域",
            HorizontalAlignment = HorizontalAlignment.Center,
            VerticalAlignment = VerticalAlignment.Center,
            Foreground = new SolidColorBrush(Colors.White),
            FontWeight = FontWeights.Bold
        };

        imageBorder.Child = imageText;

        // 设置图片对齐
        switch (_currentStyle.ImageStyle.Alignment)
        {
            case ImageAlignment.Left:
                imageBorder.HorizontalAlignment = HorizontalAlignment.Left;
                break;
            case ImageAlignment.Center:
                imageBorder.HorizontalAlignment = HorizontalAlignment.Center;
                break;
            case ImageAlignment.Right:
                imageBorder.HorizontalAlignment = HorizontalAlignment.Right;
                break;
        }

        PreviewPanel.Children.Add(imageBorder);

        // 图片说明
        if (_currentStyle.ImageStyle.ShowCaption)
        {
            var captionBlock = CreateImageCaptionBlock("图片说明: 这是一个示例图片的说明文字");
            PreviewPanel.Children.Add(captionBlock);
        }

        // 图片设置信息
        var settingsInfo = $"图片设置 - 对齐: {_currentStyle.ImageStyle.Alignment} | " +
                          $"最大尺寸: {_currentStyle.ImageStyle.MaxWidth} × {_currentStyle.ImageStyle.MaxHeight} | " +
                          $"显示说明: {(_currentStyle.ImageStyle.ShowCaption ? "是" : "否")}";

        var settingsBlock = new TextBlock
        {
            Text = settingsInfo,
            FontSize = 10,
            Foreground = new SolidColorBrush(Colors.Gray),
            Margin = new Thickness(0, 15, 0, 0),
            TextWrapping = TextWrapping.Wrap
        };
        PreviewPanel.Children.Add(settingsBlock);

        if (_currentStyle.ImageStyle.ShowCaption)
        {
            var captionInfo = $"说明文字 - 字体: {_currentStyle.ImageStyle.CaptionFontName} | " +
                             $"字号: {_currentStyle.ImageStyle.CaptionFontSize} | " +
                             $"颜色: {_currentStyle.ImageStyle.CaptionColor} | " +
                             $"对齐: {_currentStyle.ImageStyle.CaptionAlignment}";

            var captionInfoBlock = new TextBlock
            {
                Text = captionInfo,
                FontSize = 10,
                Foreground = new SolidColorBrush(Colors.Gray),
                Margin = new Thickness(0, 5, 0, 0),
                TextWrapping = TextWrapping.Wrap
            };
            PreviewPanel.Children.Add(captionInfoBlock);
        }
    }

    private TextBlock CreateStyledTextBlock(string text, DocumentTitleStyle style)
    {
        var textBlock = new TextBlock
        {
            Text = text,
            FontFamily = new FontFamily(style.FontName),
            FontSize = style.FontSize,
            FontWeight = style.IsBold ? FontWeights.Bold : FontWeights.Normal,
            FontStyle = style.IsItalic ? FontStyles.Italic : FontStyles.Normal
        };

        // 设置颜色
        try
        {
            var color = (Color)ColorConverter.ConvertFromString(style.Color);
            textBlock.Foreground = new SolidColorBrush(color);
        }
        catch
        {
            textBlock.Foreground = new SolidColorBrush(Colors.Black);
        }

        // 设置对齐
        switch (style.Alignment)
        {
            case Models.TextAlignment.Left:
                textBlock.TextAlignment = System.Windows.TextAlignment.Left;
                break;
            case Models.TextAlignment.Center:
                textBlock.TextAlignment = System.Windows.TextAlignment.Center;
                break;
            case Models.TextAlignment.Right:
                textBlock.TextAlignment = System.Windows.TextAlignment.Right;
                break;
            case Models.TextAlignment.Justify:
                textBlock.TextAlignment = System.Windows.TextAlignment.Justify;
                break;
        }

        return textBlock;
    }

    private TextBlock CreateStyledTextBlock(string text, HeadingStyle style)
    {
        var textBlock = new TextBlock
        {
            Text = text,
            FontFamily = new FontFamily(style.FontName),
            FontSize = style.FontSize,
            FontWeight = style.IsBold ? FontWeights.Bold : FontWeights.Normal,
            FontStyle = style.IsItalic ? FontStyles.Italic : FontStyles.Normal
        };

        // 设置颜色
        try
        {
            var color = (Color)ColorConverter.ConvertFromString(style.Color);
            textBlock.Foreground = new SolidColorBrush(color);
        }
        catch
        {
            textBlock.Foreground = new SolidColorBrush(Colors.Black);
        }

        // 设置对齐
        switch (style.Alignment)
        {
            case Models.TextAlignment.Left:
                textBlock.TextAlignment = System.Windows.TextAlignment.Left;
                break;
            case Models.TextAlignment.Center:
                textBlock.TextAlignment = System.Windows.TextAlignment.Center;
                break;
            case Models.TextAlignment.Right:
                textBlock.TextAlignment = System.Windows.TextAlignment.Right;
                break;
            case Models.TextAlignment.Justify:
                textBlock.TextAlignment = System.Windows.TextAlignment.Justify;
                break;
        }

        return textBlock;
    }

    private TextBlock CreateStyledTextBlock(string text, TextStyle style)
    {
        var textBlock = new TextBlock
        {
            Text = text,
            FontFamily = new FontFamily(style.FontName),
            FontSize = style.FontSize,
            FontWeight = style.IsBold ? FontWeights.Bold : FontWeights.Normal,
            FontStyle = style.IsItalic ? FontStyles.Italic : FontStyles.Normal
        };

        // 设置颜色
        try
        {
            var color = (Color)ColorConverter.ConvertFromString(style.Color);
            textBlock.Foreground = new SolidColorBrush(color);
        }
        catch
        {
            textBlock.Foreground = new SolidColorBrush(Colors.Black);
        }

        // 设置对齐
        switch (style.Alignment)
        {
            case Models.TextAlignment.Left:
                textBlock.TextAlignment = System.Windows.TextAlignment.Left;
                break;
            case Models.TextAlignment.Center:
                textBlock.TextAlignment = System.Windows.TextAlignment.Center;
                break;
            case Models.TextAlignment.Right:
                textBlock.TextAlignment = System.Windows.TextAlignment.Right;
                break;
            case Models.TextAlignment.Justify:
                textBlock.TextAlignment = System.Windows.TextAlignment.Justify;
                break;
        }

        return textBlock;
    }

    private TextBlock CreateImageCaptionBlock(string text)
    {
        var style = _currentStyle.ImageStyle;
        var textBlock = new TextBlock
        {
            Text = text,
            FontFamily = new FontFamily(style.CaptionFontName),
            FontSize = style.CaptionFontSize,
            FontStyle = style.CaptionItalic ? FontStyles.Italic : FontStyles.Normal,
            Margin = new Thickness(0, 5, 0, 0)
        };

        // 设置颜色
        try
        {
            var color = (Color)ColorConverter.ConvertFromString(style.CaptionColor);
            textBlock.Foreground = new SolidColorBrush(color);
        }
        catch
        {
            textBlock.Foreground = new SolidColorBrush(Colors.Black);
        }

        // 设置对齐
        switch (style.CaptionAlignment)
        {
            case ImageAlignment.Left:
                textBlock.TextAlignment = System.Windows.TextAlignment.Left;
                break;
            case ImageAlignment.Center:
                textBlock.TextAlignment = System.Windows.TextAlignment.Center;
                break;
            case ImageAlignment.Right:
                textBlock.TextAlignment = System.Windows.TextAlignment.Right;
                break;
        }

        return textBlock;
    }

    private void OK_Click(object sender, RoutedEventArgs e)
    {
        SaveCurrentSettings();
        DialogResult = true;
        Close();
    }

    private void Cancel_Click(object sender, RoutedEventArgs e)
    {
        DialogResult = false;
        Close();
    }

    private void RefreshPresetsList()
    {
        var currentSelectedIndex = PresetComboBox.SelectedIndex;
        var currentSelectedName = (PresetComboBox.SelectedItem as ExportStyle)?.Name;
        
        _presetStyles = ExportStyle.GetAllPresets();
        PresetComboBox.ItemsSource = _presetStyles;
        
        // 尝试保持之前的选择
        if (!string.IsNullOrEmpty(currentSelectedName))
        {
            var index = Array.FindIndex(_presetStyles, p => p.Name == currentSelectedName);
            if (index >= 0)
            {
                PresetComboBox.SelectedIndex = index;
                return;
            }
        }
        
        // 如果找不到之前的选择，尝试使用之前的索引
        if (currentSelectedIndex >= 0 && currentSelectedIndex < _presetStyles.Length)
        {
            PresetComboBox.SelectedIndex = currentSelectedIndex;
        }
        else if (_presetStyles.Length > 0)
        {
            PresetComboBox.SelectedIndex = 0;
        }
    }
    
    private void SaveCurrentSettings()
    {
        // 保存文档标题设置
        _currentStyle.DocumentTitle.FontName = DocTitleFontComboBox.SelectedItem?.ToString() ?? "微软雅黑";
        if (int.TryParse(DocTitleSizeTextBox.Text, out int docTitleSize))
            _currentStyle.DocumentTitle.FontSize = docTitleSize;
        _currentStyle.DocumentTitle.Color = DocTitleColorTextBox.Text;
        if (Enum.TryParse<Models.TextAlignment>(DocTitleAlignComboBox.SelectedItem?.ToString(), out var docTitleAlign))
            _currentStyle.DocumentTitle.Alignment = docTitleAlign;
        _currentStyle.DocumentTitle.IsBold = DocTitleBoldCheckBox.IsChecked ?? false;
        _currentStyle.DocumentTitle.IsItalic = DocTitleItalicCheckBox.IsChecked ?? false;
        
        // 保存各级标题设置
        for (int i = 0; i < 6; i++)
        {
            var level = i + 1;
            var heading = _currentStyle.HeadingStyles[i];
            
            var fontCombo = FindName($"Heading{level}FontComboBox") as ComboBox;
            var sizeTextBox = FindName($"Heading{level}SizeTextBox") as TextBox;
            var colorTextBox = FindName($"Heading{level}ColorTextBox") as TextBox;
            var boldCheckBox = FindName($"Heading{level}BoldCheckBox") as CheckBox;
            var italicCheckBox = FindName($"Heading{level}ItalicCheckBox") as CheckBox;
            
            if (fontCombo?.SelectedItem != null)
                heading.FontName = fontCombo.SelectedItem.ToString()!;
            if (sizeTextBox != null && int.TryParse(sizeTextBox.Text, out int headingSize))
                heading.FontSize = headingSize;
            if (colorTextBox != null)
                heading.Color = colorTextBox.Text;
            if (boldCheckBox != null)
                heading.IsBold = boldCheckBox.IsChecked ?? false;
            if (italicCheckBox != null)
                heading.IsItalic = italicCheckBox.IsChecked ?? false;
        }
        
        // 保存正文设置
        _currentStyle.BodyText.FontName = BodyFontComboBox.SelectedItem?.ToString() ?? "微软雅黑";
        if (int.TryParse(BodySizeTextBox.Text, out int bodySize))
            _currentStyle.BodyText.FontSize = bodySize;
        _currentStyle.BodyText.Color = BodyColorTextBox.Text;
        if (Enum.TryParse<Models.TextAlignment>(BodyAlignComboBox.SelectedItem?.ToString(), out var bodyAlign))
            _currentStyle.BodyText.Alignment = bodyAlign;
        _currentStyle.BodyText.IsBold = BodyBoldCheckBox.IsChecked ?? false;
        _currentStyle.BodyText.IsItalic = BodyItalicCheckBox.IsChecked ?? false;
        if (float.TryParse(LineSpacingTextBox.Text, out float lineSpacing))
            _currentStyle.BodyText.LineSpacing = lineSpacing;
        if (int.TryParse(ParagraphSpacingTextBox.Text, out int paragraphSpacing))
            _currentStyle.BodyText.ParagraphSpacing = paragraphSpacing;
        
        // 保存页面设置
        if (Enum.TryParse<PageSize>(PageSizeComboBox.SelectedItem?.ToString(), out var pageSize))
            _currentStyle.PageSettings.PageSize = pageSize;
        if (Enum.TryParse<PageOrientation>(OrientationComboBox.SelectedItem?.ToString(), out var orientation))
            _currentStyle.PageSettings.Orientation = orientation;
        
        if (float.TryParse(TopMarginTextBox.Text, out float top))
            _currentStyle.PageSettings.Margins.Top = top;
        if (float.TryParse(BottomMarginTextBox.Text, out float bottom))
            _currentStyle.PageSettings.Margins.Bottom = bottom;
        if (float.TryParse(LeftMarginTextBox.Text, out float left))
            _currentStyle.PageSettings.Margins.Left = left;
        if (float.TryParse(RightMarginTextBox.Text, out float right))
            _currentStyle.PageSettings.Margins.Right = right;
        
        // 保存图片设置
        if (Enum.TryParse<ImageAlignment>(ImageAlignComboBox.SelectedItem?.ToString(), out var imageAlign))
            _currentStyle.ImageStyle.Alignment = imageAlign;
        _currentStyle.ImageStyle.ShowCaption = ShowCaptionCheckBox.IsChecked ?? true;
        if (int.TryParse(MaxWidthTextBox.Text, out int maxWidth))
            _currentStyle.ImageStyle.MaxWidth = maxWidth;
        if (int.TryParse(MaxHeightTextBox.Text, out int maxHeight))
            _currentStyle.ImageStyle.MaxHeight = maxHeight;
        
        _currentStyle.ImageStyle.CaptionFontName = CaptionFontComboBox.SelectedItem?.ToString() ?? "微软雅黑";
        if (int.TryParse(CaptionSizeTextBox.Text, out int captionSize))
            _currentStyle.ImageStyle.CaptionFontSize = captionSize;
        _currentStyle.ImageStyle.CaptionColor = CaptionColorTextBox.Text;
        if (Enum.TryParse<ImageAlignment>(CaptionAlignComboBox.SelectedItem?.ToString(), out var captionAlign))
            _currentStyle.ImageStyle.CaptionAlignment = captionAlign;
    }
}

/// <summary>
/// ExportStyle扩展方法
/// </summary>
public static class ExportStyleExtensions
{
    public static ExportStyle DeepClone(this ExportStyle source)
    {
        var json = System.Text.Json.JsonSerializer.Serialize(source);
        return System.Text.Json.JsonSerializer.Deserialize<ExportStyle>(json)!;
    }
}

// 简单的输入对话框
public partial class InputDialog : Window
{
    public string Result { get; private set; } = "";

    public InputDialog(string message, string title, string defaultValue = "")
    {
        InitializeComponent();
        Title = title;
        MessageTextBlock.Text = message;
        InputTextBox.Text = defaultValue;
        InputTextBox.SelectAll();
        InputTextBox.Focus();
    }

    private void OK_Click(object sender, RoutedEventArgs e)
    {
        Result = InputTextBox.Text;
        DialogResult = true;
    }

    private void Cancel_Click(object sender, RoutedEventArgs e)
    {
        DialogResult = false;
    }
} 